﻿using UnityEngine;
using UnityEngine.Events;

public class ClickHandler : MonoBehaviour
{
    private Ray ray;
    private RaycastHit hit;
    private bool first = true;//是否结束标记
    private bool flag = true;//单击或双击标记，默认单击
    public UnityEvent OnClicsListener;//单击事件监听
    public UnityEvent OnDbClickListener;//双击事件监听

    private void Update()
    {
        Monitor();
    }

    private void Monitor()
    {
        //鼠标左键点击
        if (!Input.GetMouseButtonDown(0))
            return;

        //射线检测到的对象是当前对象
        if (Camera.main != null)
            ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if (!Physics.Raycast(ray, out hit) || hit.collider.gameObject != gameObject)
            return;


        flag = !flag;

        //上一次的事件是否已经执行完了，
        if (!first)
            return;
        first = false;

        //初始化定时器，300毫秒后执行
        Invoke("Timer", 0.3f);
    }

    private void Timer()
    {
        if(flag)
        {
            OnDbClickListener.Invoke();
        }
        else
        {
            OnClicsListener.Invoke();
        }

        //定时调用结束，重置标志
        first = true;
        flag = true;
    }
}